$(function () {
    var query = {}, fields = 'id|userName|password|name|gender|phone',
        $search = $('.search'), $searchBar = $('.search-btn');
    var config = {
        coloum_num: 8, //列数目
        query: '/saleCashApply/query?',//分页查询URL,
        create: '/order/create',//create,
        update: '/order/update',
        check: '/saleCashApply/check',
        'delete': '/order/delete',
        pay: '/saleCashApply/pay',
        valid: '/saleperson/valid',
    };
    $searchBar.click(function () {
        $(this).button('loading');
        console.log({keyword: $search.val()});
        search({keyword: $search.val()});

    });
    function search(obj,isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        var arg = [];
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        query = query_;query.timestamp = Date.now(); 
        $.get(config.query + arg.join('&'), function (res) {
            $searchBar.button('reset');
            if (res.list.length) {
                render(res.list)
            } else {
                render(noData(config.coloum_num));
                $('.reset-query').click(function () {
                    $search.val('');
                    $searchBar.click();
                })
            }
            var page = res.page;
            pageInit(page,query,search)


        });
    }

    function render(list) {
        // $('.table-responsive .table tbody')

        $('.table-responsive .table tbody').html('');
        if (list instanceof Array) {
            list.forEach(function (item, index) {
                // re
                $('.table-responsive .table tbody')
                    .append('<tr> \
                    <td scope="row">' + (index + 1) + ' \
                </td> \
                <td>' + item.no + '</td> \
                <td>' + (item.saleName) + '</td> \
                <td>' + (item.name||'') + '</td> \
                <td>' + (item.phone) + '</td> \
                <td>' + (item.idCard) + '</td> \
                <td>' + (item.valid == 0 ? '未验证' : '已验证') + '</td> \
                <td>' + (item.bankName) + '</td> \
                <td>' + (item.bankAccount) + '</td> \
                <td>' + item.applyCount + '</td> \
                <td>' + (item.status == 0 ? '申请中' : (item.status == 1 ? '待打款' : (item.status == 2 ? '拒绝' : (item.status == 3 ? '已打款' : '')))) + '</td> \
                <td>' + (item.refuseReason || '') + '</td> \
                <td>' + moment(item.createAt).format('YYYY-MM-DD HH:mm:ss') + '</td> \
            <td class="text-right"> \
                <div class="btn-group" role="group" style="width: 113px;"> \
                ' + (item.valid == 0 ? '<button type="button" class="btn btn-xs  btn-danger interactive opt-valid" \
                data-json=\'' + JSON.stringify(item) + '\' >身份证验证通过</button>' : '')
                        + ((item.valid == 1 && item.status == 0) ? '<button type="button" class="btn btn-xs  btn-danger interactive opt-check" \
                data-toggle="modal" data-target=" .order-check" \
                data-json=\'' + JSON.stringify(item) + '\' >审核</button>' : (item.valid=='2'?('<span class="tag tag-danger">拒绝,'+item.validReason+'</span>'):'')) +
                        ((item.valid == 1 && item.status == 1) ? '<button data-id="' + item.id + '" type="button" class="btn btn-xs  btn-danger interactive opt-pay" \
                            >确认打款</button>' : '')
                        + '\
                </div> \
                </td> \
                </tr>')
            });
            $('.opt-valid').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var item = $(this).data('json');
                var $json = $(this).data('json');
                _alert({
                    title: '验证通过该用户身份证信息',
                    body: '<textarea class="form-control applyEndReason" placeholder="处理说明.."></textarea>',
                    okbtn: '通过',
                    cancelbtn: '拒绝',
                    hasfoot: true,
                    okHide: function (event) {
                        if ($(event.target).text().indexOf('通过') > -1) {
                            $.post("/ladingBill/destroy", {
                                id: $json.saleId,
                                valid: 1,
                                validReason: $('.applyEndReason').val()
                            }, function (data) {
                                if (data.code == 200) {
                                    search({}, true);
                                } else {
                                    alert(data.error)
                                }
                            })
                        }
                    },
                    cancelHide: function (event) {
                        if ($(event.target).text().indexOf('拒绝') > -1) {
                            var $refuse = $('.applyEndReason');
                            if (!$refuse.val()) {
                                fnFail("请填写处理说明？");
                                return false;
                            }
                            $.post(config.check, {
                                id: $json.id,
                                saleId: $json.saleId,
                                valid: 2,
                                status: 2,
                                refuseReason: $refuse.val(),
                                validReason: $refuse.val()
                            }, function (data) {
                                if (data.code == 200) {
                                    search({}, true);
                                } else {
                                    alert(data.error)
                                }
                            })
                        }
                    },
                })

            });

            $('.opt-pay').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var self = this;
                $(this).button('loading');

                var item = $(this).data('id');
                if (confirm('您确认已经打款？')) {
                    $.post(config.pay, {id: item, status: '3'}, function (xhr, data) {
                        $(self).button('reset');
                        search({},true);
                    });
                } else {
                    $(self).button('reset');
                }
            });
        } else {
            $('.table-responsive .table tbody').html(list);
        }
        $loading.fadeOut();
    }

    $('.order-check').on('show', function (event) {
        var button = $(event.relatedTarget);
        var recipient = button.data('json');
        var modal = $(this);
        modal.find('.modal-title').text('审核佣金提现');
        modal.find('.modal-title').data('id', recipient.id);
    }).on('okHide', function (event) {
        var $id = $(event.target).closest('.modal-content').find('.modal-title').data('id');
        if ($(event.target).text().indexOf('通过') > -1) {
            $.post(config.check, {
                id: $id,
                status: 1,
            }, function (data) {
                if (data.code == 200) {
                    search({},true);
                    $('.order-check').modal('hide');
                } else {
                    alert(data.error)
                }
            })
        } else if ($(event.target).text().indexOf('拒绝') > -1) {
            var $refuse = $('.hp-refuse');
            if (!$refuse.val()) {
                return $refuse.addClass('hp-input-error')
            } else {
                $refuse.removeClass('hp-input-error');
            }
            $.post(config.check, {
                id: $id,
                status: 2,
                refuseReason: $refuse.val()
            }, function (data) {
                if (data.code == 200) {
                    search({},true);
                    $('.order-check').modal('hide');
                } else {
                    alert(data.error)
                }
            })
        }
    });
    search({},true);

    // 表单提交
    var $submit = $('#submit');
    $submit.on('click', function () {
        var $btn = $(this).button('loading');
    });

    $("#user-form").validate({
        submitHandler: function (form_) {
            var form = {};
            fields.split('|').map(function (item) {
                form[item] = form_[item].value
            });
            var url = config.create;
            if (form.id) { // is update?
                url = config.update;
            } else {
                delete form.id;
            }
            $.post(url, form, function (xhr, data) {
                $submit.button('reset');
            });
            return false;
        }
    });
    $('.table th .fa').click(function (e) {
        var sort = {sortField: '', sortOrder: ''};
        sort.sortField = $(this).data('sort');
        if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
            sort.sortOrder = 'ASC';
            $(this)
                .removeClass('fa-sort-desc fa-sort')
                .addClass('fa-sort-asc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort');
        } else if ($(this).hasClass('fa-sort-asc')) { //asc
            sort.sortOrder = 'DESC';
            $(this)
                .removeClass('fa-sort-asc fa-sort')
                .addClass('fa-sort-desc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort')
        }
        search(sort);
    })
});